<template>
  <div class="data-form coupon-form" v-loading.fullscreen.lock="loading">
    <el-form label-width="70px" size="medium">
      <el-form-item label="批次名称">
        <span v-if="hasReadonly">{{couponForm.stockName}}</span>
        <el-input v-else v-model="couponForm.stockName" class="form-input">
        </el-input>
      </el-form-item>

      <template v-if="user.branchId===1">
        <el-form-item label="所属店铺" v-if="hasReadonly">
          <span>{{couponForm.shopName}}</span>
        </el-form-item>

        <template v-else>
          <el-form-item label="所属总店">
            <el-select filterable v-model="couponForm.branchId" class="form-input" :disabled="inputLoading" @change="branchChange">
              <el-option v-for="branch in branchList" :key="branch.branchId" :value="branch.branchId" :label="branch.branchName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属分店">
            <el-select filterable clearable v-model="couponForm.partnerId" class="form-input" :disabled="inputLoading">
              <el-option v-for="partner in partnerList" :key="partner.id" :value="partner.id" :label="partner.name">
              </el-option>
            </el-select>
          </el-form-item>
        </template>
      </template>

      <el-form-item label="面额">
        <span v-if="hasReadonly">{{couponForm.couponAmount}}分={{formatMoney(couponForm.couponAmount)}}元</span>
        <template v-else>
          <el-input-number v-model="couponForm.couponAmount" class="momeny-input" :min="1" :controls="false" :precision="0">
          </el-input-number>
          <span>分={{formatMoney(couponForm.couponAmount)}}元</span>
        </template>
      </el-form-item>
      <el-form-item label="门槛">
        <span v-if="hasReadonly">{{couponForm.transactionMinimum}}分={{formatMoney(couponForm.transactionMinimum)}}元</span>
        <template v-else>
          <el-input-number v-model="couponForm.transactionMinimum" class="momeny-input" :min="1" :controls="false" :precision="0">
          </el-input-number>
          <span>分={{formatMoney(couponForm.transactionMinimum)}}元</span>
        </template>
      </el-form-item>
      <el-form-item label="发放数量">
        <span v-if="hasReadonly">{{couponForm.maxCoupons}}</span>
        <el-input-number v-else v-model="couponForm.maxCoupons" class="form-input" :min="1" :controls="false" :precision="0">
        </el-input-number>
      </el-form-item>
      <el-form-item>
        <div slot="label" class="double-row">单日最多发放数量</div>

        <span v-if="hasReadonly">{{couponForm.maxCount}}张={{maxDayMoney}}元</span>
        <template v-else>
          <el-input-number v-model="couponForm.maxCount" class="momeny-input" :min="1" :controls="false" :precision="0">
          </el-input-number>
          <span>张={{maxDayMoney}}元</span>
        </template>
      </el-form-item>
      <el-form-item label="有效时间">
        <span v-if="hasReadonly">
          {{$moment(couponForm.startTime).format('YYYY-MM-DD HH:mm')}}至{{$moment(couponForm.endTime).format('YYYY-MM-DD HH:mm')}}
        </span>

        <template v-else>
          <sys-date-time-picker v-model="couponForm.startTime" class="time-input" format="yyyy-MM-dd HH:mm" type="minute"
            :disabled-date="disabledDate">
          </sys-date-time-picker>
          <span>至</span>
          <sys-date-time-picker v-model="couponForm.endTime" class="time-input" format="yyyy-MM-dd HH:mm" type="minute" :disabled-date="disabledDate">
          </sys-date-time-picker>
        </template>
      </el-form-item>
      <el-form-item label="说明">
        <sys-area-input v-model="couponForm.description" class="form-input" :maxlength="3000" :autosize="true" :has-escape="false"
          :disabled="hasReadonly">
        </sys-area-input>
      </el-form-item>
      <el-form-item>
        <div slot="label" class="double-row">用户可领数量</div>

        <span v-if="hasReadonly">{{couponForm.maxCouponsPerUser}}</span>
        <el-input-number v-else v-model="couponForm.maxCouponsPerUser" class="form-input" :min="1" :max="60" :controls="false" :precision="0"
          placeholder="每个用户最多领取60张券">
        </el-input-number>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="couponForm.combineUse" :true-label="1" :false-label="0" :disabled="hasReadonly">可与其他优惠叠加使用</el-checkbox>
      </el-form-item>
    </el-form>

    <div style="text-align:center" v-if="type==='add'">
      <el-button size="medium" type="primary" @click="saveCoupon">新增</el-button>
    </div>
  </div>
</template>

<script>
  import PermissionApi from 'services/permissionApi';
  import CouponMgrApi from 'services/couponMgrApi';
  import loginUser from 'mixins/loginUser';

  import SysDateTimePicker from 'commonComponents/sysDateTimePicker';
  import SysAreaInput from 'commonComponents/sysAreaInput';

  import CouponForm from 'models/couponMgr/couponForm';

  export default {
    mixins: [loginUser],

    props: {
      coupon: {
        type: Object,
        default () {
          return null
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      dropdownOption: {
        type: Object,
        default () {
          return {};
        }
      }
    },

    computed: {
      maxDayMoney() {
        let couponForm = this.couponForm;
        let couponAmount = couponForm.couponAmount;
        let maxCount = couponForm.maxCount;
        if (couponAmount === undefined || maxCount === undefined) {
          return 0;
        }
        let totalMoney = couponAmount * maxCount;
        return _.round(totalMoney / 100, 2);
      },
      hasReadonly() {
        return this.type === 'look';
      }
    },

    data() {
      let couponForm;
      if (this.type === 'add') {
        couponForm = new CouponForm();
      } else {
        couponForm = _.cloneDeep(this.coupon);
      }
      return {
        loading: false,
        inputLoading: false,
        couponForm,
        nowTime: this.$moment().valueOf(),
        statusList: this.i18n.getDropDown('couponMgr.status', [1, 0]),
        stopStatusList: this.i18n.getDropDown('couponMgr.stopStatus', [1, 0]),
        disabledDate: time => {
          return !this.checkValidTime(time);
        },
        branchList: [],
        partnerList: []
      };
    },

    created() {
      if (this.hasReadonly || this.user.branchId !== 1) {
        return;
      }

      this.inputLoading = true;
      this.setBranchList().then(() => {
        this.inputLoading = false;
      }).catch(() => {
        this.inputLoading = false;
      });
    },

    methods: {
      setBranchList() {
        let dropdownOption = this.dropdownOption;
        let branchList = dropdownOption.branchList;
        if (branchList !== undefined) {
          this.branchList = branchList;
          return Promise.resolve(branchList);
        }

        return PermissionApi.getBranchList().then(branchList => {
          this.branchList = branchList;
          dropdownOption.branchList = branchList;
          return branchList;
        });
      },

      setPartnerList() {
        let branchId = this.couponForm.branchId;
        if (branchId === '') {
          this.partnerList = [];
          return Promise.resolve([]);
        }
        return PermissionApi.getPartners(branchId).then(partnerList => {
          this.partnerList = partnerList;
          return partnerList;
        });
      },

      branchChange() {
        this.inputLoading = true;
        this.setPartnerList().then(() => {
          this.couponForm.partnerId = '';
          this.inputLoading = false;
        }).catch(() => {
          this.inputLoading = false;
        });
      },

      saveCoupon() {
        let couponForm = this.couponForm;
        let code = couponForm.checkValid(this.user, this.nowTime);
        if (code !== '') {
          let msg = this.i18n.getMsg(`couponMgr.couponTable.error.${code}`);
          this.$message(msg);
          return;
        }

        if (this.type === 'add') {
          this.addCoupon(couponForm);
        }
      },

      addCoupon(couponForm) {
        this.loading = true;
        CouponMgrApi.addGoupon(couponForm).then(msg => {
          this.loading = false;
          this.$alert(msg, '信息', {
            callback: () => {
              this.$emit('save-success');
            }
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      checkValidTime(time) {
        return this.$moment(time).isSameOrAfter(this.nowTime, 'day');
      },

      formatMoney(money) {
        if (money === undefined) {
          return 0;
        }
        return _.round(money / 100, 2);
      }
    },

    components: {
      SysDateTimePicker,
      SysAreaInput
    }
  };

</script>

<style lang="scss" scoped>
  @import '~viewStyle/dataForm';

  .coupon-form {
    .double-row {
      line-height: 20px;
    }

    .time-input {
      width: 175px;
    }

    .momeny-input {
      width: 200px;
    }
  }

</style>
